package com.cskaoyan.service;

import com.cskaoyan.bean.bo.AuthPermissionsBO;
import com.cskaoyan.bean.pojo.Authority;
import com.cskaoyan.bean.pojo.AuthorityExample;
import com.cskaoyan.bean.Info;
import com.cskaoyan.bean.data.BaseData;
import com.cskaoyan.bean.param.AdminParam;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.data.AdminData;

import com.cskaoyan.bean.vo.RoleOptionsVo;
import com.cskaoyan.bean.vo.Perm;
import com.cskaoyan.bean.vo.PermissionRole;
import com.cskaoyan.bean.vo.RolePermissionVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.bean.pojo.AdminExample;
import com.cskaoyan.bean.pojo.Role;
import com.cskaoyan.bean.pojo.RoleExample;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：dailin
 * @date ：
 * @description：
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    LogMapper logMapper;


    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    AllPermissionsMapper allPermissionsMapper;

    @Autowired
    AuthorityApiMapper authorityApiMapper;

    @Autowired
    AuthorityMapper authorityMapper;


    @Override
    public BaseData<Admin> selectAllAdmin(AdminParam adminParam) {
        //查询之前，使用分页插件
        PageHelper.startPage(adminParam.getPage(), adminParam.getLimit());
        AdminExample adminExample = new AdminExample();
        //排序信息

        adminExample.setOrderByClause(adminParam.getSort() + "  " + adminParam.getOrder());
        AdminExample.Criteria criteria = adminExample.createCriteria();
        if (adminParam.getUsername() != null && !"".equals(adminParam.getUsername())) {
            criteria.andUsernameLike("%" + adminParam.getUsername() + "%");
        }

        criteria.andDeletedEqualTo(false);

        //查询所有的管理员，模糊查询
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        PageInfo<Admin> adminPageInfo = new PageInfo<>(admins);
        long total = adminPageInfo.getTotal();
        AdminData adminData = new AdminData();

        return BaseData.ok(admins, total);
    }


    /**
     * 后面的都是shiro权限验证新加，勿删
     *
     * @param username
     * @return
     */
    @Override
    public Admin selectAdminByUsername(String username) {
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andDeletedEqualTo(false);
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        return admins.size() >= 1 ? admins.get(0) : null;
    }

    @Override
    public String selectPasswordByUsername(String username) {
        return adminMapper.selectPasswordByUsername(username);

    }

    @Override
    public Info selectAdminInfoByUsername(String username) {
        //第一步先查出admin
        Info info = new Info();
        Admin admin = selectAdminByUsername(username);
        System.out.println(admin);//null
        Integer[] roleIds = admin.getRoleIds();
        List<String> roleNames = selectRoleNameListByIds(roleIds);
        ArrayList<String> perms = new ArrayList<>();
        for (Integer roleId : roleIds) {
            perms.addAll(selectPermsByRoleId(roleId));
            System.out.println(roleId.toString());
        }
        info.setName(admin.getUsername());
        info.setPerms(perms);
        info.setAvatar(admin.getAvatar());
        info.setRoles(roleNames);
        return info;
    }

    @Override
    public List<String> selectPermsByRoleId(Integer roleId) {
        ArrayList<String> permsList = new ArrayList<>();
        if (roleId == 1) {
            permsList.add("*");
            return permsList;
        }
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andRoleIdEqualTo(roleId);
        List<Permission> permissions = permissionMapper.selectByExample(permissionExample);
        for (Permission permission : permissions) {
            //根据权限id拿到权限名
            int permId = allPermissionsMapper.queryPermIdByPermName(permission.getPermission());
            String permApiName = authorityApiMapper.queryApiNameByPermId(permId);
            permsList.add(permApiName);
        }
        return permsList;
    }

    @Override
    public List<String> selectRoleNameListByIds(Integer[] roleIds) {
        ArrayList<String> roleNameList = new ArrayList<>();
        for (Integer roleId : roleIds) {
            RoleExample roleExample = new RoleExample();
            RoleExample.Criteria criteria = roleExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andIdEqualTo(roleId);
            List<Role> roles = roleMapper.selectByExample(roleExample);
            for (Role role : roles) {
                roleNameList.add(role.getName());
            }
        }
        return roleNameList;
    }

    @Override
    public List<RoleOptionsVo> selectAllRole1() {
        RoleExample roleExample = new RoleExample();
        //查询管理员级别和权限
        List<Role> roles = roleMapper.selectByExample(roleExample);
        ArrayList<RoleOptionsVo> roleOptionsVos = new ArrayList<>();
        for (Role role : roles) {
            RoleOptionsVo roleOptionsVo = new RoleOptionsVo();
            roleOptionsVo.setLabel(role.getName());
            roleOptionsVo.setValue(role.getId());
            roleOptionsVos.add(roleOptionsVo);
        }
        return roleOptionsVos;
    }

    @Override
    public Integer addAdmin(Admin admin) {
        AdminExample adminExample = new AdminExample();
        admin.setDeleted(false);
        Date date = new Date();
        admin.setAddTime(date);

        int effectRow = adminMapper.insert(admin);
        return effectRow;
    }

    @Override
    public int deleteAdmin(Admin admin) {
        admin.setDeleted(true);
        int i = adminMapper.updateByPrimaryKey(admin);
        if (i == 1) {
            return 1;
        }
        return 0;
    }

    @Override
    public Admin updateAdmin(Admin admin) {
        int i = adminMapper.updateByPrimaryKey(admin);
        if (i == 1) {
            return admin;
        }
        return null;
    }

    @Override
    public BaseData<Log> logList(AdminParam adminParam) {
        PageHelper.startPage(adminParam.getPage(), adminParam.getLimit());
        LogExample logExample = new LogExample();
        LogExample.Criteria criteria = logExample.createCriteria();
        if (adminParam.getName() != null && !"".equals(adminParam.getName())) {
            criteria.andAdminLike("%" + adminParam.getName() + "%");
        }
        List<Log> logs = logMapper.selectByExample(logExample);
        long total = logMapper.countByExample(logExample);
        return BaseData.ok(logs, total);
    }



    /**
     * 后面的是 权限配置
     * @param roleId
     * @return
     */
    @Override
    public RolePermissionVO getPermissions(Integer roleId) {
        List<PermissionRole> perms = new ArrayList<>();
        List<String> assignedPerms = new ArrayList<>();
        perms = getAllPermissions();
        assignedPerms = getPermissionsById(roleId);
        RolePermissionVO permissionVO = new RolePermissionVO();
        permissionVO.setSystemPermissions(perms);
        permissionVO.setAssignedPermissions(assignedPerms);
        return permissionVO;
        //todo
    }

    @Override
    public void roleAuthorization(AuthPermissionsBO permissionsBO) {
        Date date = new Date();
        //删除原来所有
        int i = deletePermissionsByRoleId(permissionsBO.getRoleId());

        //再新增
        for (String permissionName : permissionsBO.getPermissions()) {
            Permission permission = new Permission();
            permission.setRoleId(permissionsBO.getRoleId());
            permission.setPermission(permissionName);
            permission.setAddTime(date);
            permission.setUpdateTime(date);
            permission.setDeleted(false);
            permissionMapper.insertSelective(permission);
        }
    }

    private int deletePermissionsByRoleId(Integer id) {
        Date date = new Date();
        Permission permission = new Permission();
        permission.setUpdateTime(date);
        permission.setDeleted(true);

        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andRoleIdEqualTo(id);
        criteria.andDeletedEqualTo(false);

        int i = permissionMapper.updateByExampleSelective(permission, permissionExample);
        return i;
    }


    private List<String> getPermissionsById(Integer roleId) {
        List<String> stringList = new ArrayList<>();

        if (roleId == 1) {
            stringList = getAllPermissionsNames();
            return stringList;
        }

        //查permissions
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        criteria.andDeletedEqualTo(false);

        List<Permission> permissions = permissionMapper.selectByExample(permissionExample);
        for (Permission permission : permissions) {
            stringList.add(permission.getPermission());
        }
        return stringList;
    }

    /**
     * @description: 获取超级管理员的所有权限名称
     * @param:
     * @return: List<String>
     */
    private List<String> getAllPermissionsNames() {
        AllPermissionsExample allPermissionsExample = new AllPermissionsExample();
        AllPermissionsExample.Criteria criteria = allPermissionsExample.createCriteria();
        criteria.andIdNotEqualTo(1);
        criteria.andDeletedEqualTo(false);
        List<AllPermissions> allPermissions = allPermissionsMapper.selectByExample(allPermissionsExample);

        List<String> stringList = new ArrayList<>();

        for (AllPermissions permission : allPermissions) {

            stringList.add(permission.getPermission());
        }
        return stringList;
    }

    private List<PermissionRole> getAllPermissions() {
        List<PermissionRole> systemPermissions = new ArrayList<>();

        AuthorityExample authorityExample = new AuthorityExample();
        AuthorityExample.Criteria criteria = authorityExample.createCriteria();
        criteria.andPidEqualTo(0);
        criteria.andDeletedEqualTo(false);

        List<Authority> authorities = authorityMapper.selectByExample(authorityExample);
        for (Authority authority : authorities) {
            PermissionRole<PermissionRole> PermissionRoles = new PermissionRole();
            PermissionRoles.setId(authority.getLabel());
            PermissionRoles.setLabel(authority.getLabel());
            PermissionRoles.setChildren(getNestedPermission(authority.getId()));
            systemPermissions.add(PermissionRoles);
        }
        return systemPermissions;
    }

    private List<PermissionRole> getNestedPermission(Integer id) {
        List<PermissionRole> children = new ArrayList<>();

        AuthorityExample authorityExample = new AuthorityExample();
        AuthorityExample.Criteria criteria = authorityExample.createCriteria();
        criteria.andPidEqualTo(id);
        criteria.andDeletedEqualTo(false);

        List<Authority> authorities = authorityMapper.selectByExample(authorityExample);
        for (Authority authority : authorities) {
            PermissionRole<Perm> PermissionRoles = new PermissionRole();
            PermissionRoles.setId(authority.getLabel());
            PermissionRoles.setLabel(authority.getLabel());
            PermissionRoles.setChildren(getPermissionsApi(authority.getId()));
            children.add(PermissionRoles);
        }
        return children;
    }

    private List<Perm> getPermissionsApi(Integer id) {
        List<Perm> children = new ArrayList<>();

        AuthorityApiExample authorityApiExample = new AuthorityApiExample();
        AuthorityApiExample.Criteria criteria = authorityApiExample.createCriteria();
        criteria.andAuthorityIdEqualTo(id);
        criteria.andDeletedEqualTo(false);
        List<AuthorityApi> authorityApis = authorityApiMapper.selectByExample(authorityApiExample);
        for (AuthorityApi authorityApi : authorityApis) {
            Perm permissionApi = new Perm();
            permissionApi.setLabel(authorityApi.getLabel());
            permissionApi.setApi(authorityApi.getApi());
            //查all_permissions表
            permissionApi.setId(getPermissionsName(authorityApi.getPermissionId()));
            children.add(permissionApi);
        }
        return children;
    }

    private String getPermissionsName(Integer id) {
        AllPermissionsExample allPermissionsExample = new AllPermissionsExample();
        AllPermissionsExample.Criteria criteria = allPermissionsExample.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andDeletedEqualTo(false);

        List<AllPermissions> allPermissions = allPermissionsMapper.selectByExample(allPermissionsExample);
        if (allPermissions.isEmpty()) {
            return null;
        }
        AllPermissions allPermissions1 = allPermissions.get(0);
        return allPermissions1.getPermission();
    }


}
